java善假于物(四):生成缩略图

介绍

我们开发中经常遇到这样的业务需求,比如用户上传一张大头像,但是不是所有展示页面我们都给用户看到那张大图,那样会降低加载速度,影响用户体验,而且浪费流量,那我们要怎么做才能生成缩略图呢?

开源地址:https://github.com/bigbeef
个人博客:http://blog.cppba.com

我们先看一下效果:

最终效果

创建缩略图生成工具类ImgCompressUtil .java(核心)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package com.cppba.core.util;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* 图片压缩处理
* @author 大黄蜂coder
*/
public class ImgCompressUtil {
/**
* 强制压缩/放大图片到固定的大小
* @param fileName 压缩文件("c:\\1.png")
* @param compressPercent 压缩比例(压缩为原来一半传0.5)
* @return
*/
public static BufferedImage resize(String fileName,double compressPercent){
BufferedImage img = null;//原图
BufferedImage compressImg = null;//压缩后图
int width,height;
try {
File file = new File(fileName);
img = ImageIO.read(file);
width = (int)(img.getWidth()*compressPercent);
height = (int)(img.getHeight()*compressPercent);
compressImg = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB );
compressImg.getGraphics().drawImage(img, 0, 0, width, height, null); // 绘制缩小后的图
} catch (IOException e) {
e.printStackTrace();
}
return compressImg;
}
/**
*
* @param file 存放位置("c:\\1.png")
* @param img
*/
public static void writeToFile(String file,BufferedImage img){
try {
File destFile = new File(file);
FileOutputStream out = new FileOutputStream(destFile); // 输出到文件流
ImageIO.write(img, "png", out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

测试类ImgCompress.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.cppba.main;
import com.cppba.core.util.ImgCompressUtil;
import java.awt.image.BufferedImage;
public class ImgCompress {
public static void main(String[] args) {
String fileName = "f:\\ImgTest\\bg.jpg";
BufferedImage bufferedImage = ImgCompressUtil.resize(fileName, 0.5);
ImgCompressUtil.writeToFile(fileName+"_middle.png", bufferedImage);
BufferedImage img = ImgCompressUtil.resize(fileName, 0.25);
ImgCompressUtil.writeToFile(fileName+"_small.png", img);
}
}

运行结果

缩略图生成

生成成功!我这里用了一个技巧,中型缩略图和小型缩略图直接改他们的后缀名,这样用起来也非常方便,要某张图的缩略图,直接跟个后缀就可以了,当然大家可以根据自己的业务需求修改源代码,生成自己想要的大小!